
window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitTransaction || window.msTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
window.IDBCursor = window.IDBCursor || window.webkitIDBCursor || window.msIDBCursor;
var dbName = 'Data';
var dbVersion = '2017';
var idb, datatable;
var data;
//网页加载时执行
function window_onload() {
    var dbConnect = window.indexedDB.open(dbName, dbVersion);//打开数据库
    dbConnect.onsuccess = function (e) {
        idb = e.target.result;
        datatable = document.getElementById("datatable");
    };
    dbConnect.onerror = function () {
        console.log("数据库连接失败");
    };
    //如果对象仓库orders不存在，建立orders,数据库需更新版本号
    dbConnect.onupgradeneeded = function (e) {
        idb = e.target.result;
        if (!idb.objectStoreName.contains('orders')) {
            var tx = e.target.transaction;
            tx.oncomplete = function () {
                console.log("对象仓创建成功")
            }
            tx.onabort = function (e) {       //对象仓库创建失败时触发
                console.log('对象仓库创建失败')
            };
            //创建对象仓库，var store = db.createObjectStore("orders", {keyPath: "id"});
            var storename = 'orders';
            var optionalParameters = {
                keyPah: 'id',
                autoIncrement: true                           //id自动编号
            };
            var store = idb.createObjectStore(storename, optionalParameters);//创建表
            cnosole.log('对象仓库创建成功');
            //创建索引
            var indexname = 'codeIndex';
            var keyPath = 'code';
            var optionalParameters = {
                unique: true,
                multiEntry: false
            };
            var idx = store.createIndex(indexname, keyPath, optionalParameters);//创建数索引
            console.log('索引创建成功');
        }
    };
}

//数量文本框失去焦点时触发
function num_onblur() {
    var num, price;
    num = parseInt(document.getElementById("num").value);
    price = parseFloat(document.getElementById("price").value);
    if (isNaN(num * price)) {                               //isNaN()判断是否为非法数字
        document.getElementById("num").value = "0";
        document.getElementById("money").value = "0";
    }
    else
        document.getElementById("money").value = num * price;
}
//单价文本框失去焦点时触发
function price_onblur() {
    var num, price;
    num = parseInt(document.getElementById("num").value);
    price = parseFloat(document.getElementById("price").value);
    if (isNaN(num * price)) {
        document.getElementById("num").value = "0";
        document.getElementById("money").value = "0";
    }
    else
        document.getElementById("money").value = num * price;
}
//单击追加按钮时触发
function btnAdd_onclick() {
    data = new Object();
    data.Code = document.getElementById("orderID").value;
    data.Date = document.getElementById("orderDate").value;
    data.LineName = document.getElementById("lineName").value;
    data.Employee = document.getElementById("employeeName").value;
    data.Num = document.getElementById("num").value;
    data.Price = document.getElementById("price").value;
    data.Customer = document.getElementById("theCustomer").value;////////
    data.Mobile = document.getElementById("theMobile").value;
    var tx = idb.transaction(['orders'], "readwrite");  //启动事务处理
    //var store = transaction.objectStore("orders");          // 添加数据
    var chkErrorMsg = "";
    //在追加数据以后执行
    tx.oncomplete = function () {
        if (chkErrorMsg != "")
            alert(chkErrorMsg);
        else {
            alert('追加数据成功');
            showAllData(false);
            btnNew_onclick();
        }
    }
    tx.onabort = function () {
        alert('追加数据失败');
    }
    var store = tx.objectStore('orders');   //打开交易tx获取objectStore
    var idx = store.index('codeIndex');
    var range = IDBKeyRange.only(data.Code);//只取当前索引值为data.Code的数据
    var direction = "next";
    var req = idx.openCursor(range, direction);//打开游标
    req.onsuccess = function () {
        var cursor = this.result;
        if (cursor) {
            chkErrorMsg = "输入的订单编号在数据库中已经存在！";
        }
        else {
            var value = {
                code: data.Code,
                date: data.Date,
                linename: data.LineName,
                employee: data.Employee,
                num: data.Num,
                price: data.Price,
                customer: data.Customer,
                mobile: data.Mobile
            };
            store.put(value);
        }
    }
    req.onerror = function () {
        alert('追加数据失败');
    }
}
//修改订单信息
function btnUpdate_onclick() {
    data = new Object();
    data.Code = document.getElementById("orderID").value;
    data.Date = document.getElementById("orderDate").value;
    data.LineName = document.getElementById("lineName").value;
    data.Employee = document.getElementById("employeeName").value;
    data.Num = document.getElementById("num").value;
    data.Price = document.getElementById("price").value;
    data.Customer = document.getElementById("theCustomer").value;
    data.Mobile = document.getElementById("theMobile").value;
    var tx = idb.transaction(['orders'], "readwrite");
    tx.oncomplete = function () {
        console.log('修改数据成功');
        showAllData(false);
    }
    tx.onabort = function () {
        console.log('修改数据失败');
    }
    var store = tx.objectStore('orders');
    var idx = store.index('codeIndex');
    var range = IDBKeyRange.only(data.Code);
    var direction = "next";
    var req = idx.openCursor(range, direction);
    req.onsuccess = function () {
        var cursor = this.result;
        if (cursor) {
            var value = {
                code: data.Code,
                date: data.Date,
                linename: data.LineName,
                employee: data.Employee,
                num: data.Num,
                price: data.Price,
                customer: data.Customer,
                mobile: data.Mobile
            };
            cursor.update(value);
        }
    }
    req.onerror = function () {
        console.log('修改数据失败');
    }
}
//删除订单
function btnDelete_onclick() {
    var tx = idb.transaction(['orders'], "readwrite");
    tx.oncomplete = function () {       //删除成功之后触发
        alert("删除数据成功");
        showAllData(false);
        btnNew_onclick();
    }
    tx.onabort = function () {
        alert('删除数据失败');
    }
    var store = tx.objectStore('orders');
    var idx = store.index('codeIndex');
    var range = IDBKeyRange.only(document.getElementById("orderID").value);
    var direction = "next";
    var req = idx.openCursor(range, direction);
    req.onsuccess = function () {
        var cursor = this.result;
        if (cursor) {
            cursor.delete();
        }
    }
    req.onerror = function () {
        alert('删除数据失败');
    }
}
function btnNew_onclick() {
    document.getElementById("form1").reset();
    //reset()把表单中元素设为默认值
    document.getElementById("orderID").removeAttribute("readonly");
    document.getElementById("btnAdd").disabled = "";
    document.getElementById("btnUpdate").disabled = "disabled";
    document.getElementById("btnDelete").disabled = "disabled";
}
function tr_onclick(tr, i) {
    document.getElementById("orderID").value = tr.children.item(0).innerHTML;  //innerHTML是一个字符串用于获取位于对象起始到结束的内容
    document.getElementById("orderDate").value = tr.children.item(1).innerHTML;
    document.getElementById("lineName").value = tr.children.item(2).innerHTML;
    document.getElementById("employeeName").value = tr.children.item(3).innerHTML;
    document.getElementById("num").value = tr.children.item(4).innerHTML;
    document.getElementById("price").value = tr.children.item(5).innerHTML;
    document.getElementById("money").value = tr.children.item(6).innerHTML;
    document.getElementById("theCustomer").value = tr.children.item(7).innerHTML;
    document.getElementById("theMobile").value = tr.children.item(8).innerHTML;
    document.getElementById("orderID").setAttribute("readonly", true);
    document.getElementById("btnAdd").disabled = "disabled";
    document.getElementById("btnUpdate").disabled = "";
    document.getElementById("btnDelete").disabled = "";
}
function showAllData(loadPage) {
    if (!loadPage)
        removeAllData();
    var tx = idb.transaction(['orders'], "readonly");//创建事务
    var store = tx.objectStore('orders');
    var idx = store.index('codeIndex');
    var range = IDBKeyRange.lowerBound(1);
    var direction = "next";
    var req = idx.openCursor(range, direction);
    var i = 0;
    req.onsuccess = function () {
        var cursor = this.result;
        if (cursor) {
            i += 1;
            showData(cursor.value, i);
            cursor.continue();
        }
    }
    req.onerror = function () {
        alert('检索数据失败');
    }
}
function removeAllData() {
    for (var i = datatable.childNodes.length - 1; i > 1; i--)
        datatable.removeChild(datatable.childNodes[i]);
}
function showData(row, i) {                                  //cursor.value 相当于 row（是对象）
    var tr = document.createElement('tr');                   //生成一个新控件tr
    tr.setAttribute("onclick", "tr_onclick(this," + i + ")"); //为控件添加属性
    var td1 = document.createElement('td');                 //生成一个新控件td
    td1.innerHTML = row.code;
    var td2 = document.createElement('td');
    td2.innerHTML = row.date;
    var td3 = document.createElement('td');
    td3.innerHTML = row.linename;
    var td4 = document.createElement('td');
    td4.innerHTML = row.employee;
    var td5 = document.createElement('td');
    td5.innerHTML = row.num;
    var td6 = document.createElement('td');
    td6.innerHTML = row.price;
    var td7 = document.createElement('td');
    td7.innerHTML = parseInt(row.num) * parseFloat(row.price);
    var td8 = document.createElement('td');
    td8.innerHTML = row.customer;
    var td9 = document.createElement('td');
    td9.innerHTML = row.mobile;
    tr.appendChild(td1);         //添加该节点
    tr.appendChild(td2);
    tr.appendChild(td3);
    tr.appendChild(td4);
    tr.appendChild(td5);
    tr.appendChild(td6);
    tr.appendChild(td7);
    tr.appendChild(td8);
    tr.appendChild(td9);
    datatable.appendChild(tr);
}

